Sound = {}
Sound.__index = Sound

function Sound:load()
     -- Sound effects
     heartbeat = love.audio.newSource('Sound/28895__junggle__btn085.wav', 'static')
     heartbeat:setVolume(10)
     pulse = love.audio.newSource('Sound/30668__hardpcm__hardbassdrum002.wav', 'static')
     -- Different Source for each track
     musicUpbeat = {}
     setmetatable(musicUpbeat, Sound)
     musicUpbeat = love.audio.newSource("Sound/copter_-_zero8.mp3", "stream")
     musicUpbeat:setLooping(true)
     
     musicDownbeat = {}
     setmetatable(musicDownbeat, Sound)
     musicDownbeat = love.audio.newSource("Sound/SunriseOnMars.mp3", "stream")
     musicDownbeat:setLooping(true)
     
     -- Start with the downbeat track
     trackToPlay = musicDownbeat
     
     trackToPlay:play()
     
     musicFade = false
     timeSinceFade = 0
end

function Sound:update(dt, playerHealth, glowHealth)
     currTime = love.timer.getTime()
     if gameOver then
          Sound:fadeOut(dt)
     elseif playerHealth < 2500 or glowHealth < 2000 then
          if trackToPlay == musicDownbeat and (currTime - timeSinceFade) > 30 then 
               Sound:fadeOut(dt)
          end
          if musicFade == false and trackToPlay:getVolume() == 0 then
               trackToPlay:stop()
               trackToPlay = musicUpbeat
               trackToPlay:setVolume(0)
               timeSinceFade = love.timer.getTime()
               trackToPlay:play()
          end
          if trackToPlay == musicUpbeat then 
               Sound:fadeIn(dt)
          end
     elseif playerHealth > 2500 and glowHealth > 2000 then
          if trackToPlay == musicUpbeat and (currTime - timeSinceFade) > 30 then 
               Sound:fadeOut(dt)
          end
          if musicFade == false and trackToPlay:getVolume() == 0 then
               trackToPlay:stop()
               trackToPlay = musicDownbeat
               trackToPlay:setVolume(0)
               timeSinceFade = love.timer.getTime()
               trackToPlay:play()
          end
          if trackToPlay == musicDownbeat then 
               Sound:fadeIn(dt)
          end
     end
end

function Sound:pulse()
     love.audio.play(pulse)
end

function Sound:beat()
     if heartbeat:isStopped() == false then
          heartbeat:stop()
     end
     love.audio.play(heartbeat)
end

function Sound:fadeOut(dt)
     musicFade = true
     origVol = trackToPlay:getVolume()
     currVol = origVol - dt*0.2
     if currVol < 0 then
          currVol = 0
     end
     if currVol == 0 then
          musicFade = false
     end
     trackToPlay:setVolume(currVol)
end

function Sound:fadeIn(dt)
     musicFade = true
     origVol = trackToPlay:getVolume()
     currVol = origVol + dt*0.4
     if currVol > 1 then
          currVol = 1
     end
     if currVol == 1 then
          musicFade = false
     end
     trackToPlay:setVolume(currVol)
end